package com.tfkj.contrller;


import com.amazonaws.AmazonServiceException;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.tfkj.Config;
import com.tfkj.entity.Image;
import com.tfkj.service.AllService;
import com.tfkj.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.util.*;

import static com.tfkj.Config.*;
import static com.tfkj.contrller.PdfUtil.cropPDFPage;
import static com.tfkj.contrller.PdfUtil.getImageFromURL;

@Slf4j
@RestController
@CrossOrigin(maxAge = 3600)
@RequestMapping("/image")
@Api(value = "题目",tags = "题目接口")
public class ImageController {


    @Autowired
    private Config config;

    @Autowired
    private AllService allService;



    @ApiOperation("框选学号位置")
    @PostMapping("/createNum")
    public CommonReturn createImage(@RequestBody Image vo) throws Exception {
        String preFileName = String.valueOf(new Date().getTime());
        String[] ps = vo.getPosition().split(",");
        InputStreamDTO image = cropPDFPage(getImageFromURL(vo.getUrl()), Integer.valueOf(ps[1]), Integer.valueOf(ps[3]), vo.getHeight());
        String key = preFileName + "_" + vo.getTestId()+ "_" + 0 + ".png";
        System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
        AmazonS3 s3 = config.amazonS3();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/png");
        objectMetadata.setContentLength(image.getLength());
        try {
            s3.putObject(bucket, key, image.getInputStream(), objectMetadata);
            System.out.format("Uploading %s to S3 bucket %s...\n", key, bucket);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
            System.exit(1);
        }
        System.out.println("Done!");
        Integer i = allService.createImage(vo.getTestId(), url + key, 0, 1, vo.getPosition(), vo.getWidth(), vo.getHeight(), "");
        System.out.println("修改行数："+ i);

        return new CommonReturn(200, "创建成功！");
    }

    @ApiOperation("补充题目类型和难度")
    @PostMapping("/update")
    public CommonReturn updateImage(@RequestBody UpdateImageVO vo) {
        if (vo.getTestType() != null && !"".equals(vo.getTestType())) {
            Integer i = allService.updateImageAndSaveQuestion(vo);
            System.out.println("修改行数："+ i);
            return new CommonReturn(200, "更新成功,同步题库！");
        } else {
            Integer i = allService.updateImage(vo.getId(), vo.getGrade(), vo.getSubject(), vo.getQuestionType(), vo.getDifficulty(), vo.getResult());
            System.out.println("修改行数："+ i);
            return new CommonReturn(200, "更新成功！");
        }

    }


    @ApiOperation("框选题目保存到题库")
    @PostMapping("/createImages")
    public CommonReturn makeImage(@RequestBody CreateImageListVO vos) throws Exception {
        Map<String, BufferedImage> urls = new HashMap<>();
        String preFileName = String.valueOf(new Date().getTime());
        int index = 0;
        List<CreateImageVO> imageList = new ArrayList<>();
        for (CreateImageVO vo : vos.getVos()){
            if (!urls.containsKey(vo.getUrl())){
                urls.put(vo.getUrl(), getImageFromURL(vo.getUrl()));
            }
            String[] ps = vo.getPosition().split(",");
            InputStreamDTO image = cropPDFPage(urls.get(vo.getUrl()), Integer.valueOf(ps[1]), Integer.valueOf(ps[3]), vo.getHeight());
            String key = preFileName + "_" + index + ".png";
            System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
            AmazonS3 s3 = config.amazonS3();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/png");
            objectMetadata.setContentLength(image.getLength());
            try {
                s3.putObject(bucket, key, image.getInputStream(), objectMetadata);
                System.out.format("Uploading %s to S3 bucket %s...\n", key, bucket);
            } catch (AmazonServiceException e) {
                System.err.println(e.getErrorMessage());
                System.exit(1);
            }
            index++;
            CreateImageVO createImageVO = new CreateImageVO();
            createImageVO.setPosition(vo.getPosition());
            createImageVO.setWidth(vo.getWidth());
            createImageVO.setHeight(vo.getHeight());
            createImageVO.setSortNum(vo.getSortNum());
            createImageVO.setPageNum(vo.getPageNum());
            createImageVO.setGrade(vos.getGrade());
            createImageVO.setSubject(vos.getSubject());
            createImageVO.setUrl(url + key);
            System.out.println(createImageVO);
            imageList.add(createImageVO);
        }
        allService.createImage(imageList, vos.getTestId());
        return new CommonReturn(200, "上传成功！");
    }


    @ApiOperation("查询截图列表-by测验id")
    @GetMapping("/list")
    public CommonReturn list(@RequestParam("testId") Integer testId) {
        List<ImageWithGradeAndSubjectVO> list = allService.findImage(testId);
        return new CommonReturn(list);
    }


}
